package dianmobile.eistarandroid.utils;

import android.text.Html;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 这个类的静态方法用于处理字符串，转换为需要的格式
 * Created by dianmobile_yy on 15/11/15.
 */
public class HandleString {

    private static String dateFormat1 = "yyyy年MM月dd日HH:mm";
    private static String dateFormat2= "MMM dd HH:mm:ss yyyy";

    /**
     * 处理时间字符串，转换为时间差格式的字符串
     * 计算输入时间到当前时间的时间差，如果时间差小于0，直接返回输入时间
     * @param inputDateString 输入的时间
     * @return 规定格式的时间差字符串
     */
    public static String getTimeDifference(String inputDateString) {

        if (inputDateString == null) {
            return null;
        }
        Date nowDate = new Date(System.currentTimeMillis());
        Date inputDate = null;

        SimpleDateFormat format = null;
        if (inputDateString.contains("日")) {
            format = new SimpleDateFormat(dateFormat1, Locale.CHINESE);
        }else {
            if (inputDateString.length() > 22){//Wed Dec  9 20:21:51 2015  去掉前面的星期
                inputDateString = inputDateString.substring(4).trim();
            }
            format = new SimpleDateFormat(dateFormat2, Locale.US);
        }


        try {
            String nowDateStr = format.format(nowDate);
            inputDate = format.parse(inputDateString);
            nowDate = format.parse(nowDateStr);
        } catch (ParseException | NullPointerException e) {
            e.printStackTrace();
        }

        if (inputDate == null || nowDate == null) {
            return null;
        }
        long timeLong = nowDate.getTime() - inputDate.getTime();    //时间差：单位ms

        if (timeLong < 0) {
            return inputDateString;
        } else if (timeLong < 60 * 1000)   //小于一分钟
            return "刚刚";
        else if (timeLong < 60 * 60 * 1000) {   //小于一小时
            timeLong = timeLong / 1000 / 60;
            return timeLong + "分钟前";
        } else if (timeLong < 60 * 60 * 24 * 1000) {    //小于1天
            timeLong = timeLong / 60 / 60 / 1000;
            return timeLong + "小时前";
        } else {
            long dayLong = timeLong / 1000 / 60 / 60 / 24;      //时间差，单位day
            if (dayLong < 7) {                  //小于一周
                return dayLong + "天前";
            } else if(dayLong < 30) {           //小于一月
                return dayLong/7 + "周前";
            } else if (dayLong < 365) {
                return dayLong/30 + "月前";       //小于一年
            } else {
                return dayLong/365 + "年前";
            }
        }

    }

    /**
     * 处理文章详情字符串，去掉开头的发信信息和结尾的签名档
     * @param source 文章详情
     * @return 去掉签名档的文章
     */
    public static String handleArticleDetail(String source) {
        //去掉开头的发信信息
        String s[] = source.split("\\n");
        StringBuffer buffer = new StringBuffer();
        for(int i = 3; i < s.length - 2; i++) {
            if(!s[i].contains("\n")) {
                buffer.append(s[i] + "\n");
            }
        }
        return buffer.toString();
//        去掉结尾的签名档
//        String resultArticle;
//        String strings[] = buffer.toString().split("--\\n");
//        resultArticle = strings[0];
//        return resultArticle;
//        return source;
    }

    /**
     * 处理文章列表中的summary字符串，去掉结尾的签名档
     * @param source 文章详情
     * @return 去掉签名档的文章
     */
    public static String handleArticleSummary(String source) {

        //去掉结尾的签名档
        String resultArticle;
        String strings[] = source.split("--\\n");
        resultArticle = strings[0];
        return resultArticle;
    }

    /**
     * 判断editview内容是否为空
     *
     * @param input String
     * @return
     */
    public static boolean isEmpty(String input) {
        if ("".equals(input)) {
            return true;
        }
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n')) {
                return false;
            }
        }
        return true;
    }


    /**
     * 取文章的前三非空行作为摘要
     * @param detail 原文
     * @return 摘要
     */
    public static String getSummary(String detail) {
        StringBuffer buffer = new StringBuffer();
        String[] strings = detail.split("\\n");
        String tmp;
        int j = 0;
        for (String string : strings) {

            if (!HandleString.isEmpty(string)) {
                tmp = ": " + string;
                buffer.append(Html.fromHtml(tmp)).append("\n");
                j++;
            }
            if (string.contains(" 的大作中提到: ")) {
                j = 0;
            }
            if (j >= 3) {
                break;
            }
        }
        if(j >= 3){
            buffer.append(": .................（以下省略）\n");
        }
        return buffer.toString();
    }

    /**
     * 获取文本中的信息
     * @param content
     * @return
     */
    public static String[] parsePostContent(String content) {
        if (content == null) {
            return null;
        }
//        content = content.replace("\\n", "\n").replace("\\r", "\r")
//                .replace("\\/", "/").replace("\\\"", "\"").replace("\\'", "'");
        String[] lines = content.split("\\n");
        StringBuilder sb = new StringBuilder();
        String author = "未知";
        String dateString = "";
        int linebreak = 0;
        for (String line : lines) {
            if (line.startsWith("发信人:") || line.startsWith("寄信人:")) {
                author = subStringBetween(line, ":", ",");
                continue;
            } else if (line.startsWith("标  题:")) {
                continue;
            } else if (line.startsWith("发信站:")) {
                dateString = subStringBetween(line, "(", ")");
                continue;
            }

            if (line.equals("")) {
                linebreak++;
                if (linebreak > 1) {
                    continue;
                }
            } else {
                linebreak = 0;
            }
            sb.append(line).append("\n");
        }
        String contentResult = sb.toString();
        return new String[] {contentResult, author, dateString};
    }

    /**
     * 修改文本格式
     * @param rawContent
     * @return
     */
    public static CharSequence beautifulContent(String rawContent){
        if (rawContent == null) return null;
        String[] lines = rawContent.split("\\n");
        StringBuilder sb = new StringBuilder();
        for (String line : lines){
            if (line.startsWith(": ")) {
                line = "<font color=#848484>" + line + "</font>";
            }else if (line.equals("--")){//到了尾部，后面的信息暂时不要。
                break;
            }
            sb.append(line).append("<br />");
        }
        return Html.fromHtml(sb.toString());
    }

    private static String subStringBetween(String line, String str1, String str2) {
        int idx1 = line.indexOf(str1);
        int idx2 = line.indexOf(str2);
        return line.substring(idx1 + str1.length(), idx2);
    }
}
